package com.own.stu.apm.agent.core.plugin;

import com.own.stu.apm.agent.core.plugin.loader.AgentClassLoader;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class PluginBootstrap {
    /**
     * 加载所有生效的插件,因为是自定义的路径下的jar:
     * 1.先获取到agent.jar的路径
     * 2、使用自定义类加载器进行加载插件
     */
    public List<AbstractClassEnhencePluginDefine> loadPlugins() {
        AgentClassLoader.initDefaultLoader();
        PluginResourcesResolver pluginResourcesResolver = new PluginResourcesResolver();
        List<URL> resources = pluginResourcesResolver.getResources();
        if (resources == null || resources.size() == 0) {
            log.info("no plugins.def find");
            return new ArrayList<>();
        }

        for (URL resource : resources) {
            try {
                PluginCfg.INSTANCE.load(resource.openStream());
            } catch (IOException e) {
                log.error("plugin def file {} init fail", resource, e);
            }
        }
        List<AbstractClassEnhencePluginDefine> plugins = new ArrayList<>();
        List<PluginDefineItem> pluginClassList = PluginCfg.INSTANCE.getPluginClassList();
        for (PluginDefineItem pluginDefineItem : pluginClassList) {
            try {
                AbstractClassEnhencePluginDefine o =
                        (AbstractClassEnhencePluginDefine) Class.forName(pluginDefineItem.getClassName(), true, AgentClassLoader.getDefault())
                                .newInstance();
                plugins.add(o);
            } catch (Exception e) {
                log.error("load class {} error ", pluginDefineItem.getClassName(), e);
            }
        }
        return plugins;
    }
}
